import {useRoutes, useUserInfo} from "@/stores";
import type {Router} from "vue-router";
import type {Pinia} from "pinia";

/* 申明变量和方法等 */
const pathArr: string[] = ["/login"];

// 跳转到注册方法
const gotoLogin = (path: string, next: any) => {
  if (path === "/login") {
    next();
  } else {
    next("/login");
  }
};

const popstateFn = function() {
  // @ts-ignore
  history.pushState(null, '', document.URL)
}

export default function interceptor(router: Router, pinia: Pinia){
  /*公共路由*/
  /* 路由拦截器 */
  router.beforeEach((to, from, next) => {
    const Store = useUserInfo(pinia)
    const RoutesConfig = useRoutes(pinia)

    // 如果用户进入了登录页面就相当于退出
    if (pathArr.includes(to.path)) {
      Store.token = ''
      next()
    }
    // token写入业务存储
    if (!Store.token) {
      gotoLogin(to.fullPath, next);
    } else {
      const hasRoute = router.hasRoute(to.name!)
      if (!hasRoute) {
        RoutesConfig._addRoutes(RoutesConfig.routes, router)
        next({...to, replace: true})
      } else {
        next()
      }
    }
  });
  router.afterEach((to, from) => {
    // 清除登录页历史记录
    if (to.path == '/login' || from.path == '/login') {
      window.removeEventListener('popstate', popstateFn)
      popstateFn()
      window.addEventListener('popstate', popstateFn, false)
    }
  });
};